<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title>文件上传页面</title>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<h1>Ajax文件上传进度条</h1>
<!-- 
ajax提交后form表单中如果存在button按钮的话ajax完成之后form表单
还是会自动提交
-->
<form method="post" id="form1" name="form1"
      enctype="multipart/form-data"
      onsubmit="return false;">
    <input type="file" name="files" id="files" multiple="multiple"/>
</form>

<!-- 动画进度条 -->
<div>
    <span id="pdNum">0%</span>
</div>
<div>
    <button class="btn btn-primary" id="upload">上传</button>
    <button class="btn btn-danger" id="cancel">取消</button>
</div>
<p>开始时间:<font id="startTime" color="red"></font></p>
<p>现在时间:<font id="currentTime" color="red"></font></p>
<p>已经传输了的时间(s):<font id="time" color="red"></font></p>
<p>传输速度(byte/s):<font id="velocity" color="red"></font></p>
<p>估计总时间:<font id="totalTime" color="red"></font></p>
<p>估计剩余时间:<font id="timeLeft" color="red"></font></p>
<p>上传百分比:<font id="percent" color="red"></font></p>
<p>已完成数:<font id="length" color="red"></font></p>
<p>总长度(M):<font id="totalLength" color="red"></font></p>
<p>第几个文件:<font id="items" color="red"></font></p>
<p>文件名:<font id="name" color="red"></font></p>
</body>

<script type="text/javascript">
    let timeInfo = 0;
    let fileNames = [];

    $(function () {
        $("#upload").click(function () {
            uploadFile();
            timeInfo = setInterval("getUploadInfo()", 800);
        });

        $("#cancel").click(function () {
            clearInterval(timeInfo);
        });

    });

    //文件上传
    function uploadFile() {
        fileNames = [];
        let formData = new FormData();
        let files = $("#files")[0].files;
        for (let i = 0; i < files.length; i++) {
            formData.append("files", files[i]);
            fileNames.push(files[i].name);
        }
        console.log("开始上传..." + formData);
        $.ajax({
            type: "POST",
            url: "/upload",
            data: formData,
            async: true,
            cache: false,
            dataType: "json",
            contentType: false,/*必须false才会自动加上正确的Content-Type */
            processData: false,/*必须false才会避开jQuery对 formData 的默认处理XMLHttpRequest会对 formData 进行正确的处理*/
            success: function (res) {
                console.log(res);
                if (res.tag == true) {
                    clearInterval(timeInfo);
                    getUploadInfo();//修正得到文件上传信息
                    setPdWidth(100);//修正文件上传为100%
                    alert("上传成功!");
                } else {
                    clearInterval(timeInfo);
                    alert("上传失败!");
                }
            },
            error: function () {
                clearInterval(timeInfo);
                alert("上传错误!");
            }
        });
    }

    //得到上传文件进度信息
    function getUploadInfo() {
        $.ajax({
            url: "/getInfo",
            data: {time: new Date()},
            type: "GET",
            dataType: "json",
            cache: false,
            success: function (res) {
                console.log(res);
                setPdWidth(res.percent);
                setUploadInfo(res);
                if (res.percent >= 100) {
                    clearInterval(timeInfo);
                }
            },
            error: function () {
                clearInterval(timeInfo);
                console.log("得到上传文件信息出错!");
            }
        });
    }

    //设置上传文件进度信息
    function setUploadInfo(res) {
        $("#startTime").text(res.startTime);
        $("#currentTime").text(res.currentTime);
        $("#time").text(res.time);
        $("#velocity").text(res.velocity);
        $("#totalTime").text(res.totalTime);
        $("#timeLeft").text(res.timeLeft);
        $("#percent").text(res.percent);
        $("#length").text(res.length);
        $("#totalLength").text(res.totalLength);
        $("#items").text(res.items);
        $("#name").text(fileNames.length === 0 ? "" : fileNames[res.items - 1]);
    }

    function setPdWidth(percent) {
        $("#pdNum").text(percent + "%");
    }

</script>
</html>